const router = require('koa-router')()
const multer = require('koa-multer')
const mongoose = require('mongoose')
const fs = require('fs')
const nodepath = require('path')
const util = require('util')
const moment = require('moment')
moment.locale('zh-cn')

const rename = util.promisify(fs.rename)
const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

const upload = multer({
    dest: 'public/uploads/'
})

router.get('/', async (ctx, next) => {
    const images = await Image.find().sort({
        createdAt: -1
    }).limit(9)
    await ctx.render('index', {
        title: "imgPloadr.io",
        images
    })
})
router.post('/upload', upload.single('imagefile'), async ctx => {
    const {
        body: {
            title,
            description
        },
        file: {
            originalname,
            filename,
            path
        }
    } = ctx.req
    const ext = nodepath.extname(originalname)
    await rename(path, path + ext)
    const {
        _id
    } = await Image.create({
        title,
        description,
        originalname,
        filename: filename + ext
    })
    await ctx.redirect('/image/' + _id)
})
router.get('/image/:id', async ctx => {
    const {
        id
    } = ctx.params
    const image = await Image.findById(id)
    const images = await Image.find().sort({likes: -1}).limit(3)
    const imageAll = await Image.count()
    const commentAll = await Comment.find({ "imageid": id }, (err, doc) => {
        if(err) throw doc
    }).sort({ createdAt: -1 }).count()
    const views = await Image.findByIdAndUpdate(
        id, { $inc: { views: 1} }, { new: true }
    ).count()
    const comments = await Comment.find().sort({createdAt:-1})
    const commentMore = await Comment.find().sort({likes:-1}).limit(2)
    await ctx.render('image', {
        image,
        images,
        imageAll,
        commentAll,
        comments,
        views,
        commentMore,
        createdFromNow: moment(image.createdAt).fromNow()
    })
})

router.post('/likes', async ctx => {
    const {
        imageid
    } = ctx.request.body
    const newimage = await Image.findByIdAndUpdate(
        imageid, {
            $inc: {
                likes: 1
            }
        }, {
            new: true
        }
    )
    ctx.body = newimage
})
router.post('/views', async ctx => {
    //const { imageid } = ctx.request.body
    const newimage = await Image.findByIdAndUpdate(
        imageid, {
            $inc: {
                views: 1
            }
        }, {
            new: true
        }
    )
    ctx.body = newimage
})

//COMMENT
router.post('/comment', async ctx => {

    const {
        body: {
            name,
            email,
            comments
        },
        //  file: { commentname, filename, path }
    } = ctx.request
    //   const ext = nodepath.extname(commentname)
    //  await rename(path, path + ext)
    const {
        _id
    } = await Comment.create({
        name,
        email,
        comments
    })
    console.log(ctx.request.body)
    //await ctx.redirect('/comments/' + _id)
})


// const allimage = await Image.aggregate().group({
//     _id: id,
//     images: {
//         $sum: 1
//     },
//     views: {
//         $sum: '$views'
//     },
//     likes: {
//         $sum: '$likes'
//     }
// })




module.exports = router